<template>
  <div>
    <search @add="handleClickAction" />
    <template>
      <ms-table :table-props="tableProps" :data-api="dataUrl" ref="dataTable">
        <el-table-column label="操作" slot="tool">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleClickAction(scope.row.id, 'edit')">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleClickAction(scope.row.id, 'delete')">删除</el-button>
          </template>
        </el-table-column>
      </ms-table>
    </template>
    <info
      ref="info"
      :title="title"
      :dialog-visible="showDialog"
      :form-id="formId"
      @close="handleCloseDialog"
    />
  </div>
</template>

<script>
import { deleteStudent } from '@/api/work/student'
import Search from './Search'
import Info from './Info'
import { MsTable } from '@/common/table'
export default {
  components: {
    MsTable,
    Search,
    Info
  },
  data() {
    return {
      tableProps: [
        { index: 'name', label: '姓名' },
        { index: 'sex', label: '性别' },
        { index: 'birthday', label: '生日' }
      ],
      dataUrl: '/work/student/list',
      showDialog: false,
      formId: '',
      title: '修改'
    }
  },
  mounted() {
    this.handleGetDictSex()
  },
  methods: {
    // action事件派发
    async handleClickAction(id = '', method = 'add') {
      this.formId = id
      if (method === 'edit') {
        this.handleOpenDialog()
      } else if (method === 'delete') {
        await deleteStudent(id).then((res) => res.obj && this.handleFreshTable())
      } else if (method === 'add') {
        this.handleOpenDialog('添加')
      }
    },
    handleOpenDialog(titleName = '修改') {
      this.title = titleName
      this.showDialog = true
    },
    handleCloseDialog() {
      this.showDialog = false
      this.$refs.info.hanleResetFormData()
      this.handleFreshTable()
    },
    handleFreshTable(page, limit) {
      this.$refs.dataTable.dataFresh(page, limit)
    },
    async handleGetDictSex() {
      await this.getDict('sex').then((res) => {
        this.tableProps[1].scope = res.obj.map((item) => item.dictValue)
        this.handleFreshTable()
      })
    }
  }
}
</script>
